package com.zz.inventory.config;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zz.inventory.domain.FranchiseBills;
import com.zz.inventory.service.IFranchiseBillsService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付接口
 */
@RestController
@RequestMapping("/alipay")
public class AlipayController {

    // 支付宝沙箱网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";        //请求参数格式
    private static final String CHARSET = "UTF-8";    //字符编码
    private static final String SIGN_TYPE = "RSA2";   //签名方式

    @Resource
    private AlipayConfig alipayConfig;      //注入支付宝配置类
    @Resource
    IFranchiseBillsService iFranchiseBillsService;



    /**
     *
     * @param
     * @param httpResponse
     * @throws Exception
     */
    @GetMapping( "/pay{billId}")
    public void pay(@PathVariable Long billId, HttpServletResponse httpResponse) throws Exception {
        // 查询订单信息
        FranchiseBills orders = iFranchiseBillsService.selectFranchiseBillsByBillId(billId);      //查出订单信息
        if (orders == null){
            return;
        }
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, alipayConfig.getApp_id(),
                alipayConfig.getMerchant_private_key(), FORMAT, CHARSET, alipayConfig.getAlipay_public_key(), SIGN_TYPE);
        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 发送请求的 Request类
        request.setNotifyUrl(alipayConfig.getNotify_url());     //配置回调地址
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", orders.getBillNo()); // 我们自己生成的订单编号,必须是唯一的
        bizContent.set("total_amount", orders.getAmount()); // 订单的总金额
        bizContent.set("subject","场景购买"); // 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY"); // 固定配置
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:8080/platform/alipay/return");//设置支付成功后同步跳转地址
        // 执行请求，拿到响应的结果，返回给浏览器
        //这是支付宝官方返回的页面，再页面中进行支付
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);   //设置响应内容类型
        httpResponse.getWriter().write(form); // 直接将完整的表单html输出到页面
        // 刷新与关闭输出流
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();

    }

    /**
     * 支付宝异步通知接口（处理支付结果通知）
     * 注意：此接口必须为POST请求，且外网可访问（与AlipayConfig.notify_url一致）
     */
    @PostMapping("/notify") // 注意这里必须是POST接口
    public void payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipay_public_key(), "UTF-8");
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                String billNo = params.get("out_trade_no");     //订单编号
                String gmtPayment = params.get("gmt_payment");   //支付时间
                String alipayTradeNo = params.get("trade_no");   //支付宝交易编号

                FranchiseBills orders = iFranchiseBillsService.selectByOrderNo(billNo);   //查询订单
                orders.setStatus("已支付");
                orders.setPaymentTime(gmtPayment);
//                orders.setPayNo(alipayTradeNo);
                iFranchiseBillsService.updateById(orders);       // // 这里据库更新的语句
            }
        }
    }


    /**
     * 支付同步跳转接口（用户支付完成后跳转）
     * 注意：此接口为GET请求，仅用于页面展示，不建议依赖此接口更新订单状态
     */
    @GetMapping("/return")
    public void returnUrl(HttpServletResponse response) throws IOException {
        response.sendRedirect("http://localhost/platform/orders");
    }
}
